(function($, undefined) {
  $.cha.ns("s3");

  $.cha.js("s3.Owner");
  $.cha.js("s3.Contents");
  $.cha.js("s3.ListBucketResult");
  $.cha.js("s3.CommonPrefixes");
  $.cha.js("s3.ListAllMyBucketsResult");

  /**
   * @constructor
   */
  $.cha.s3.XmlParser = function() {
  };

  $.cha.s3.XmlParser.parseListAllMyBucketsResult = function(xml) {
    var result = new $.cha.s3.ListAllMyBucketsResult();
    result.Owner.ID = $(xml).find("Owner > ID").text();
    result.Owner.DisplayName = $(xml).find("Owner > DisplayName").text();
    $(xml).find("Bucket").each(function(i,xml){
        var bucket = new $.cha.s3.Bucket();
        bucket.CreationDate = $(xml).find("CreateDate").text();
        bucket.Name = $(xml).find("Name").text();
        result.Buckets.push(bucket);
    });
    return result;
  };

  /**
   * parse ListBackResult Xml
   * 
   * @param xml
   * @returns {$.cha.s3.ListBucketResult}
   */
  $.cha.s3.XmlParser.parseListBucketResult = function(xml) {
    var listBucketResult = new $.cha.s3.ListBucketResult();
    listBucketResult.Name = $(xml).find("ListBucketResult > Name").text();
    listBucketResult.Prefix = $(xml).find("ListBucketResult > Prefix").text();
    listBucketResult.Marker = $(xml).find("ListBucketResult > Marker").text();
    listBucketResult.MaxKeys = parseInt($(xml).find(
        "ListBucketResult > MaxKeys").text());
    listBucketResult.Delimiter = $(xml).find("ListBucketResult > Delimiter")
        .text();
    listBucketResult.IsTruncated = $(xml)
        .find("ListBucketResult > IsTruncated").text();

    $(xml).find("ListBucketResult > Contents").each(
        function(index, contents) {
          var conetnts = $.cha.s3.XmlParser.parseContents(listBucketResult,
              contents);
          listBucketResult.ContentsList.push(conetnts);
        });
    $(xml).find("ListBucketResult > CommonPrefixes").each(function(index, xml) {
      var prefix = new $.cha.s3.CommonPrefixes(listBucketResult);
      prefix.Prefix = $(xml).find("Prefix").text();
      listBucketResult.ContentsList.push(prefix);
    });
    return listBucketResult;
  };

  /**
   * parse Contents Xml
   * 
   * @param {$.cha.s3.ListBucketResult}
   * @param {Document}
   *          xml
   * @returns {$.cha.s3.Contents}
   */
  $.cha.s3.XmlParser.parseContents = function(listBucketResult, xml) {
    var contents = new $.cha.s3.Contents(listBucketResult);
    contents.Key = $(xml).find("Key").text();
    contents.Date = new Date($(xml).find("Date").text());
    contents.ETag = $(xml).find("ETag").text();
    contents.Size = parseInt($(xml).find("Size").text());
    var owner = $(xml).find("Owner");
    contents.Owner.DisplayName = $(owner).find("DisplayName").text();
    contents.Owner.ID = $(owner).find("ID").text();
    return contents;
  };
}(jQuery));